import json

from django.http import JsonResponse
from django.views.generic import View
from redis import Redis


# redis
rds = Redis(host='127.0.0.1', port=6379)

class UpdateScoreView(View):
    """分数"""
    def post(self, request):
        data = json.loads(request.body.decode())
        clt = data.get('client')
        score = data.get('score')
        # 判断用户信息是否存在
        if clt is None:
            return JsonResponse({'info': 'client error'})
        # 判断分数是否超出范围
        if score <= 0:
            JsonResponse({'info': 'Score Error'})
        if score > 10000000:
            score = 9999999

        # 存入redis：默认如果clt存在则覆盖原来的分数
        try:
            rds.zadd('score', {clt:score})
        except:
            return JsonResponse({'info': 'DBError'})
        else:
            return JsonResponse({'info': 'success'})


class GetScoreView(View):
    """查询"""
    def post(self, request):
        data = json.loads(request.body.decode())
        clt = data.get('client')
        # 用户不存在
        if clt is None:
            return JsonResponse({'info': 'client error'})
        # 查询redis
        try:
            pl = rds.pipeline()
            pl.zrevrange('score', 0, 9, withscores=True)
            pl.zrevrank('score', clt)
            pl.zscore('score', clt)
            top_rank_data, clt_rank, clt_score = pl.execute()
        except:
            return JsonResponse({'info': 'DBError'})

        # 排行榜
        top_rank = []
        for index, value in enumerate(top_rank_data):
            client = value[0].decode()
            score = int(value[1])
            top_rank.append({'rank': index+1, 'client': client, 'score': score})

        # 玩家信息
        cli_data = {
            'rank': clt_rank,
            'client': clt,
            'score': int(clt_score)
        }

        result = {'top_rank': top_rank, 'player': cli_data}
        return JsonResponse({'result': result})
